/*
* 
* @license	Apache License 2.0
* @author	Eugene Kuznetsov
*
*/
#include "CDataStorage.hpp"
#include "CDataBuffer.hpp"

CDataStorage::CDataStorage(std::string storageFile)
	: m_eState(Base::STATE_OK)
	, m_pDB(0)
{
	DBG_L1(("[%p] %s(%s)\n", this, __FUNCTION__, storageFile.c_str()));
	Int16 result = sqlite3_open(storageFile.c_str(), &m_pDB);
	if (result != SQLITE_OK)
	{
		DBG_L1(("[%p] storage couldn't be open\n", this, __FUNCTION__, storageFile.c_str()));
		m_eState = Base::STATE_NOT_OK;
	}
}

CDataStorage::~CDataStorage()
{
	DBG_L1(("[%p] %s\n", this, __FUNCTION__));
	sqlite3_close(m_pDB);
}

Base::eState CDataStorage::getState() const
{
	return m_eState;
}

Base::eState CDataStorage::ExecuteSQL(CDataBuffer* sql)
{
	DBG_L2(("[%p] %s(%s)\n", this, __FUNCTION__, sql->data()));
	Base::eState state = Base::STATE_OK;
	Chr* error_message;
	Int16 result = sqlite3_exec(m_pDB, reinterpret_cast<const char*>(sql->data()), NULL, NULL, &error_message);
	if (result != SQLITE_OK)
	{
		DBG_L2(("[%p] sqlite3_exec error -> %s\n", this, __FUNCTION__, error_message));
		sqlite3_free(error_message);
		state = Base::STATE_NOT_OK;
	}
	return state;
}

sqlite3* CDataStorage::getDB() const
{
	return m_pDB;
}
